package com.innovation.chengzhangriji.receivers;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.innovation.chengzhangriji.ChZhRJApplication;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.receivers.model.ChZhRJMessage;
import com.innovation.chengzhangriji.ui.DiscoverActivity;
import com.orhanobut.logger.Logger;
import com.xiaomi.mipush.sdk.ErrorCode;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageReceiver;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

public class MiPushReceiver extends PushMessageReceiver {

    private static final int RECEIVE_MESSAGE = 100;

    private String mRegId;
    private long mResultCode = -1;
    private String mReason;
    private String mCommand;
    private String mMessage;
    private String mTopic;
    private String mAlias;
    private String mStartTime;
    private String mEndTime;

    @Override
    public void onReceivePassThroughMessage(Context context, MiPushMessage message) {

        Logger.d("接到信息");

        LoginInfo login = Config.getLoginInfo(context);
        if (login == null) {
            return;
        }
        String content = message.getContent();
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
        ChZhRJMessage meg = gson.fromJson(content, ChZhRJMessage.class);
        if (meg == null) {
            return;
        }

        // 仅表示日记圈的新信息
        if(meg.getTag() == 1) {
            Config.setHasNewMessage(context, true);
        }

        // 显示未读数量
//        ShortcutBadger.applyCount(context, meg.getBadge());
        if (((ChZhRJApplication) context.getApplicationContext()).isApplicationLive()) {
            broadcast(context, meg.getType(), meg.getTag());
        } else {
            notification(context, meg);
        }

        mMessage = message.getContent();
        if (!TextUtils.isEmpty(message.getTopic())) {
            mTopic = message.getTopic();
        } else if (!TextUtils.isEmpty(message.getAlias())) {
            mAlias = message.getAlias();
        }
    }

    @Override
    public void onNotificationMessageClicked(Context context, MiPushMessage message) {
        mMessage = message.getContent();
        if (!TextUtils.isEmpty(message.getTopic())) {
            mTopic = message.getTopic();
        } else if (!TextUtils.isEmpty(message.getAlias())) {
            mAlias = message.getAlias();
        }
    }

    @Override
    public void onNotificationMessageArrived(Context context, MiPushMessage message) {
        mMessage = message.getContent();
        if (!TextUtils.isEmpty(message.getTopic())) {
            mTopic = message.getTopic();
        } else if (!TextUtils.isEmpty(message.getAlias())) {
            mAlias = message.getAlias();
        }
    }

    @Override
    public void onCommandResult(Context context, MiPushCommandMessage message) {
        String command = message.getCommand();
        List<String> arguments = message.getCommandArguments();
        String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
        String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);
        if (MiPushClient.COMMAND_REGISTER.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mRegId = cmdArg1;
                Config.setMiPushId(context, mRegId);
            }
        } else if (MiPushClient.COMMAND_SET_ALIAS.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mAlias = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_UNSET_ALIAS.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mAlias = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mTopic = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_UNSUBSCRIBE_TOPIC.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mTopic = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_SET_ACCEPT_TIME.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mStartTime = cmdArg1;
                mEndTime = cmdArg2;
            }
        }
    }

    @Override
    public void onReceiveRegisterResult(Context context, MiPushCommandMessage message) {
        String command = message.getCommand();
        List<String> arguments = message.getCommandArguments();
        String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
        String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);
        if (MiPushClient.COMMAND_REGISTER.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mRegId = cmdArg1;
            }
        }
    }

    private void broadcast(Context context, int type, int tag) {
        Intent intent = new Intent("ChZhRJMessage");
        intent.putExtra("ChZhRJMessageType", type);
        intent.putExtra("ChZhRJMessageTag", tag);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        if(tag != 1) { // 新评论
            Config.startLocalCommentService(context);
        }
    }

    private void notification(Context context, ChZhRJMessage msg) {
        if(msg.getTag() == 1) {
            NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.notification)
                    .setContentTitle(context.getString(R.string.app_name))
                    .setContentText(msg.getMsg());
            builder.setAutoCancel(true);
            builder.setDefaults(Notification.DEFAULT_ALL);
            builder.setLights(Color.BLUE, 300, 300);
            Intent resultIntent = new Intent(context, DiscoverActivity.class);
//            resultIntent.putExtra(Config.EXTRA_CAN_BACK, false);
            TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context).addNextIntentWithParentStack(resultIntent);
            PendingIntent resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(resultPendingIntent);
            NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = builder.build();
            try {
                notification.number = msg.getBadge();
                // MIUI Badge
                Field field = notification.getClass().getDeclaredField("extraNotification");
                Object extraNotification = field.get(notification);
                Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
                method.invoke(extraNotification, msg.getBadge());
            } catch (Exception e) {
                e.printStackTrace();
            }
            mNotificationManager.cancelAll();
            mNotificationManager.notify(0, notification);
        } else { // 评论
            Bundle bundle = new Bundle();
            bundle.putString("msg", msg.getMsg());
            bundle.putInt("badge", msg.getBadge());
            Config.startLocalCommentService(context, bundle);
        }
    }
}
